from logging import getLogger
import re

from zope.interface import Interface, implements
from zope.configuration import config, fields
from zope.schema import TextLine

from meercat.harvester.base.sources import FTPSource



log = getLogger('meercat.harvester.base')

class IFtpSource(Interface):
    host = TextLine(
        title=u'Hostname',
        description=u'FTP hostname and optional port',
        required=True)
    
    user = TextLine(
        title=u'User',
        description=u'FTP username to login with',
        required=False)
    
    passwd = TextLine(
        title=u'Password',
        description=u'FTP password to login with (requires username)',
        required=False)
    
    acct = TextLine(
        title=u'Acct',
        required=False)
    
    folder = TextLine(
        title=u'Folder',
        description=u'The folder to look for the files in, defaults to cwd',
        required=False)
    
    filter = TextLine(
        title=u'Filter',
        description=u'A regular expression to match the filename against',
        required=False)

class IFileSourceContext(Interface):
    def getFileSource(self):
        """ Return the current file source """
    
    def setFileSource(self, source):
        """ Set a new file source """

def ftpSourceHandler(context, host, filter=None, **kwargs):
    if filter:
        kwargs['_filter'] = filter
    
    if not kwargs.get('user',None):
        if kwargs.get('passwd',None):
            raise ValueError('A password cannot be set without a user')
        if kwargs.get('acct',None):
            raise ValueError('acct cannot be set without a user')
        
    return context.setFileSource(FTPSource(host=host, **kwargs))
